<template>
  <van-sticky>
    <van-search v-model="searchKey" show-action placeholder="请输入搜索关键词" @search="onSearch">
      <template #action>
        <div @click="onClickButton">搜索</div>
      </template>
    </van-search>
  </van-sticky>

  <van-list v-model:loading="loading" :finished="finished" finished-text="没有更多了" @load="onLoad">
    <div class="news-list">
      <div class="news-item" v-for="item in newsList" :key="item.id" @click="toDetail(item)">
        <div class="title">{{ item.title }}</div>
        <div class="img-list">
          <div class="img">
            <img :src="item.url" />
          </div>
        </div>
      </div>
    </div>
  </van-list>
</template>

<script setup>
import { onMounted, reactive, ref } from 'vue';
import { Toast } from 'vant';
import { useRouter } from 'vue-router';
import Api from '@/api/homePage.js';

const router = useRouter();

//新闻列表
let newsList = reactive([]);

const loading = ref(false);
const finished = ref(false);
const pageNo = ref(1);
const pageSize = ref(10);

const onLoad = () => {
  // 异步更新数据
  Api.pageList({
    pageNo: pageNo.value,
    pageSize: pageSize.value,
    title: searchKey.value,
    status: 1
  }).then(res => {
    if (pageNo.value === 1) {
      newsList = []
    }
    newsList.push(...res.data.list);

    if (newsList.length >= res.data.count) {
      finished.value = true;
    } else {
      pageNo.value++;
    }
  }).catch(() => {
    // 加载状态结束
    loading.value = false;
    finished.value = true;
  })
};
//搜索
const searchKey = ref('');
const onSearch = (val) => onClickButton();
const onClickButton = () => {
  pageNo.value = 1;
  finished.value = false;
  addSearchHistory()
  onLoad();
};

//详情
const toDetail = (row) => {
  router.push({
    name: 'newsDetail',
    query: {
      id: row.id
    }
  })
}

// 添加搜索记录
const addSearchHistory = () => {
  Api.addHistory({
    keyWords: searchKey.value,
    userId: localStorage.getItem('userId')
  })
}

onMounted(() => {
  // 请求数据
  // getNewsList();
})

</script>

<style lang="scss" scoped>
.news-list {
  padding: 0 10px;

  .news-item {
    padding: 10px 0;
    border-bottom: 1px solid #eeeeee;
  }

  .title {
    font-size: 20px;
    color: #1E1F24;
    font-weight: 600;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    margin-bottom: 5px;
  }

  .img-list {
    display: flex;
    height: 200px;

    .img {
      flex: 1;
      padding: 0 5px;

      img {
        width: 100%;
        height: 100%;
      }
    }
  }
}
</style>